<template>
  <div>
    <h3>用户列表</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>信息管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="25">
        <el-col :span="10">
          <!-- 搜索添加 -->
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- stripe隔行变色 -->
      <el-table :data="userList" border stripe style="width: 100%" height="370px">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="头像" width="120" >
        <template slot-scope="props">
          <el-image style="width: 100px; height: 100px" :src="props.row.photo" fit="cover"/>
        </template>
      </el-table-column>
        <el-table-column label="账号" prop="account"></el-table-column>
        <el-table-column label="昵称" prop="name"></el-table-column>
        <el-table-column label="角色" >
          <template slot-scope="scope">
            <span v-if="scope.row.is_vip == true">会员</span>
            <span v-if="scope.row.is_vip == false">非会员</span>
          </template>
        </el-table-column>
        <el-table-column label="会员设置" prop="is_vip">
          <!-- scope.row 就是当前行的信息 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_vip" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
      <!-- 作用域插槽 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip effect="dark" content="修改" placement="top-start" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除" placement="top-start" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 权限 -->
            <el-tooltip effect="dark" content="分配权限" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 size-change 每页最大变化 current-change 当前最大变化 layout功能组件-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top:15px">
      </el-pagination>
    </el-card>

    <!-- 创建新用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules"
        ref="addFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="账号" prop="account">
          <el-input v-model="addForm.account"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>\
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="rePassword">
          <el-input v-model="addForm.rePassword"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="昵称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <!-- 是否会员 -->
        <template>
          <el-radio v-model="addForm.is_vip" label="1">会员</el-radio>
          <el-radio v-model="addForm.is_vip" label="0">非会员</el-radio>
        </template>
      </el-form>
      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @colse="editDialogClosed">
       <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account" disabled></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="rePassword">
              <el-input v-model="editForm.rePassword"  type="password"></el-input>
            </el-form-item>
      
        <!-- 邮箱 -->
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { service, request } from '@/api/service'
export default {
  created () {
    this.getUserList()
  },
  data () {
    return {
      queryInfo: {
        query: '', // 查询信息
        pageNum: 1, // 当前页
        pageSize: 5// 每页最大数
      },
      flag:0,
      userList: [],
      total: 0, // 总记录数
      addDialogVisible: false, // 对话框状态
      // 添加用户表单项
      addForm: {
        account: '',
        password: '',
        name: '',
        is_vip: '',
        rePassword: ''
      },
      // 控制修改用户对话框显示/隐藏
      editDialogVisible: false,
      // 修改用户信息
      editForm: {
        rePassword: ''
      },
      // 修改用户表单验证规则
      editFormRules: {
        password: [
          { required: true, message: '请输入新用户密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入新用户昵称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 添加用户验证规则
      addFormRules: {
        account: [
          { required: true, message: '请输入新用户账号', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5  到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新用户密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入新用户昵称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    //获取用户列表
      getUserList(){
        request({
            url: 'getUser',
            method: 'get',
            params:this.queryInfo
        }).then(res=>{
          console.log(res.data);
            this.userList = res.data;
            this.total = res.numbers;
            let i;
            for(i=0; i<this.total; i++){
              if(this.userList[i].is_vip == 1){
                this.userList[i].is_vip = true;
              } else {
                this.userList[i].is_vip = false;
              }
            }
        })
    },
    async userStateChanged (userinfo) {
      console.log(userinfo.is_vip);
      if(userinfo.is_vip == true){
        userinfo.is_vip = 1;
      }else {
        userinfo.is_vip = 0;
      }
      request({
            url: 'userState?',
            method: 'get',
            params: {'id':userinfo.id , 'is_vip':userinfo.is_vip},
        }).then(res=>{
            if (res != 'success') {
              userinfo.id = !userinfo.id
              return this.$message.error('操作失败！！！')
            }
            this.getUserList();
            this.$message.success('操作成功！！！')
        })

    },

    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList() // 数据发生改变重新申请数据
    },
    // 监听pageNum改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList() // 数据发生改变重新申请数据
    },
    // 监听添加用户
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()// 重置表单项
    },
    RePasswd () {
      if (this.addForm.password !== this.addForm.rePassword) {
        this.$message.error('两次密码不一致！！！')
        return false
      }
      if (this.addForm.password == '' || this.addForm.rePassword == '') {
        this.$message.error('密码不能为空！！！')
        return false
      }
      return true
    },
    // 添加用户
    addUser(){
        request({
            url: 'addUser',
            method: 'get',
            params:this.addForm
        }).then(res=>{
          if (this.RePasswd()) {
            if (res != 'success') {
              return this.$message.error('操作失败！！！')
            }
            this.$message.success('操作成功！！！')
            // 隐藏
            this.addDialogVisible = false
            this.getUserList()
          }
        })
    },
    // 删除用户
    async deleteUser(id){
      // 弹框
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 成功删除为confirm 取消为 cancel
      if (confirmResult != 'confirm') {
        return this.$message.info('已取消删除')
      }
        request({
            url: 'deleteUser?id=' + id,
            method: 'get',
            params:''
        }).then(res=>{
          if (res != 'success') {
            return this.$message.error('操作失败！！！')
          }
          this.$message.success('操作成功！！！')
          this.getUserList()
        })
    },
    async showEditDialog (id) {
           request({
            url: 'getUpdate?id=' + id,
            method: 'get',
            params: ''
        }).then(res=>{
            this.editForm = res// 查询用户信息返回编辑表单
            this.editDialogVisible = true// 开启编辑对话框
        })
    },
    // 关闭窗口
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    validPasswd () {
     console.log(this.editForm.rePassword);
      if (this.editForm.rePassword == "" || this.editForm.rePassword == undefined) {
        this.$message.error('密码不能为空！！！');
        return false
      }else{
         if (this.editForm.password !== this.editForm.rePassword) {
          this.$message.error('两次密码不一致！！！')
          return false
        }
      }
      return true
    },
    // 修改用户
    editUserInfo () {
      if(this.editForm.rePassword == "" || this.editForm.rePassword == undefined){
        this.flag = 1;
      }else{
        this.flag = 0;
      }
      if (this.flag == 1){
        this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return;
        // 发起请求
        request({
            url: 'editUser',
            method: 'get',
            params: this.editForm
        }).then(res=>{
          console.log(res)
            if (res != 'success') return this.$message.error('操作失败！！！')
            this.$message.success('修改昵称成功！！！')
            // 隐藏
            this.editDialogVisible = false
            this.getUserList()
          })
        })
    }else{
        this.$refs.editFormRef.validate(async valid => {
        // 发起请求
        request({
            url: 'editUser',
            method: 'get',
            params: this.editForm
        }).then(res=>{
          console.log(res)
          if (this.validPasswd()) {
            if (res != 'success') return this.$message.error('操作失败！！！')
            this.$message.success('修改密码成功！！！')
            // 隐藏
            this.editDialogVisible = false
            this.getUserList()
            }
          })
        })
      }
    },
  }
}
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 8, 10, 0.15);
}
.el-table {
    margin-top: 15px;
    font-size: 17px;
    min-width: 350px;
}

</style>
